﻿using System;
using System.Collections.Generic;
using Opalis.QuickIntegrationKit;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Collections;

namespace Active_Directory
{
    [OpalisObject("Get Users Group Membership")]
    public class GetUserGroupMemberships : IOpalisObject
    {
        private ConnectionCredentials credentials;

        [OpalisConfiguration]
        public ConnectionCredentials Credentials
        {
            get { return credentials; }
            set { credentials = value; }
        }

        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("User LDAP Path").WithDefaultValue("LDAP://CN=UserName,OU=Container,DC=Contoso,DC=Com");
            designer.AddCorellatedData(typeof(ADObject));
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            String userLDAPPath = request.Inputs["User LDAP Path"].AsString();
            response.WithFiltering().PublishRange(getGroups(userLDAPPath));            
        }

        private IEnumerable<ADObject> getGroups(String userLDAPPath)
        {
            DirectoryEntry ent = new DirectoryEntry(userLDAPPath, credentials.UserName + "@" + credentials.Domain, credentials.Password);
            PropertyValueCollection ValueCollection = ent.Properties["memberOf"];
            foreach(String GroupDN in ValueCollection)
            {
                yield return new ADObject("LDAP://" + GroupDN);
            }
            ent.Dispose();
            ent.Close();
        }
    }
}
